from functools import wraps
# 引入蓝图
from accounts.views import accounts
from mall.views import mall

from flask import Flask, redirect, url_for, session, g, flash

from models import db, User

app = Flask(__name__)
app.config.from_object('conf.Config')
# 使用ORM
db.init_app(app)
# 注册蓝图
app.register_blueprint(accounts, url_prefix='/accounts')
app.register_blueprint(mall, url_prefix='/mall')

def login_required(view_func):
    """ 登录验证 """
    @wraps(view_func)
    def wrapper(*args, **kwargs):
        user_id = session.get('user_id', None)
        if not user_id:
            flash('请登录', 'danger')
            return redirect(url_for('accounts.login'))
        return view_func(*args, **kwargs)
    return wrapper

@app.route('/')
def index():
    return redirect(url_for('accounts.login'))

@app.before_request
def before_request():
    """ 如果有用户设置到全局对象 """
    user_id = session.get('user_id', None)
    if user_id:
        user = User.query.get(user_id)
        g.user = user
